import React from 'react';
import Input from 'shared/input';
import Axios from 'axios';
import AlertModule from 'shared/AlertModule';
import { apiPrefix } from '../../../../shared/api';

class UserForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {},
      visible: false,
      change: false,
    };
  }
  componentDidMount() {
    if (this.props.match.params.id !== undefined) {
      const api = `${apiPrefix}api/v1/unirole/user?id=${this.props.match.params.id}`;
      Axios.get(api)
        .then((response) => {
          console.log(response);
          this.setState({ user: response.data.data });
        });
    }
  }
  handleOnchange=(value, key) => {
    const { user } = this.state;
    user[key] = value;
    this.setState({ user: { ...this.state.user }, change: true });
  }
  redirectToUsers() {
    this.props.history.push('/system/users');
  }
  showAlertModule=() => {
    if (this.state.change === true) {
      this.setState({ visible: true });
    } else {
      this.redirectToUsers();
    }
  }
  closeAlertModule=() => {
    this.setState({ visible: false });
  }
  historyPush=() => {
    this.redirectToUsers();
    this.setState({ visible: false });
  }
  render() {
    const { user } = this.state;
    return (
      <div className="content">
        <div>
          <h3>添加用户</h3>
          <form>
            <div style={{ paddingLeft: 400 }}>
              <Input
                value={user.name || ''}
                label="姓名"
                inputKey="name"
                onChange={(val, key) => this.handleOnchange(val, key)}
              />
              <Input
                value={user.idcard || ''}
                label="身份证号"
                onChange={(val, key) => this.handleOnchange(val, key)}
                inputKey="idcard"
              />
              <Input
                value={user.erp_id || ''}
                label="员工编号"
                onChange={(val, key) => this.handleOnchange(val, key)}
                inputKey="erp_id"
              />
              <Input
                label="登陆账号"
                value={user.username || ''}
                inputKey="username"
                onChange={(val, key) => this.handleOnchange(val, key)}
              />
              <Input
                inputKey="password"
                label="密码"
                onChange={(val, key) => this.handleOnchange(val, key)}
              />
            </div>
            <div style={{ margin: '30px 0', paddingLeft: 600, paddingBottom: 30 }}>
              <button className="sure-button">保存</button>
              <button className="canel-button" onClick={this.showAlertModule}>取消</button>
              <AlertModule visible={this.state.visible} onCancel={this.closeAlertModule} onOk={this.historyPush} />
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default UserForm;
